package org.jfk.shiro;

import java.io.IOException;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.jfk.core.utils.StringUtils;

public class MyPermissionsAuthorizationFilter extends
		PermissionsAuthorizationFilter {
	@Override
	public boolean isAccessAllowed(ServletRequest request,
			ServletResponse response, Object mappedValue) throws IOException {
		// TODO Auto-generated method stub
		//return super.isAccessAllowed(request, response, mappedValue);

		HttpServletRequest req = (HttpServletRequest)request;
		String url = req.getRequestURI().toString();
		request.setAttribute("url", url);

		Subject subject = getSubject(request, response);
		if (subject.getPrincipal() == null) {// 表示没有登录，重定向到登录页面
//			saveRequest(request);
//			String reqUrl = super.getLoginUrl();
//			WebUtils.issueRedirect(request, response, reqUrl);
			return false;
		} else {
//			if (super.getUnauthorizedUrl() != null) {// 如果有未授权页面跳转过去
//				WebUtils.issueRedirect(request, response, super.getUnauthorizedUrl());
//			} else {// 否则返回401未授权状态码
//
//				WebUtils.toHttp(response).sendError(
//						HttpServletResponse.SC_UNAUTHORIZED);
//			}
		}
		
		
		return true;
	}

	@Override
	protected boolean onAccessDenied(ServletRequest request,
			ServletResponse response) throws IOException {

		Subject subject = getSubject(request, response);
		if (subject.getPrincipal() == null) {// 表示没有登录，重定向到登录页面
			saveRequest(request);
			WebUtils.issueRedirect(request, response, super.getLoginUrl());
		} else {
			if (super.getUnauthorizedUrl() != null) {// 如果有未授权页面跳转过去
				WebUtils.issueRedirect(request, response, super.getUnauthorizedUrl());
			} else {// 否则返回401未授权状态码

				WebUtils.toHttp(response).sendError(
						HttpServletResponse.SC_UNAUTHORIZED);
			}
		}
		return false;
	}
	
	

}
